import { BaseService } from '@/core/base.service';
import { GiftCommandDto } from '@/dtos';
import { halt } from '@/utils';
import { Injectable } from '@nestjs/common';
import { random } from 'radash';

@Injectable()
export class GiftService extends BaseService {
  async command({ command }: GiftCommandDto, userId: number) {
    return await this.redlock.using([`gift:${userId}`], 10000, {}, async () => {
      return await this.prisma.$transaction(async (tx) => {
        const user = await tx.user.findUnique({
          where: {
            id: userId,
            isBlockd: false,
            isDeleted: false,
          },
        });
        if (!user) {
          return halt('用户信息异常');
        }
        if (!user.isReal) {
          return halt('请先完成实名认证');
        }
        if (
          [
            '数链起飞',
            '苗家军集结',
            'DK助力数链',
            '清流专属罗汉福利',
            '王力团队',
            'TD助力数链起飞',
            '大鹅资本专属福利',
          ].includes(command)
        ) {
          const collection = await tx.collection.findUnique({
            where: {
              id: 1,
            },
          });
          if (!collection) {
            return halt('卡册数据异常');
          }
          if (
            (await tx.userHoldCollection.count({
              where: {
                collectionId: collection.id,
                userId: user.id,
              },
            })) <= 0
          ) {
            return halt(`您尚未拥有${collection.title}卡册`);
          }

          const count = await tx.gift.count({
            where: {
              ownerId: userId,
            },
          });
          if (count > 0) {
            return halt('每人仅限领取一次');
          }
          await tx.gift.create({
            data: {
              ownerId: userId,
              command,
            },
          });

          const camp = random(1, 18);
          const card = await tx.card.findFirst({
            where: {
              collectionId: collection.id,
              no: camp.toString(),
            },
          });
          if (!card) {
            return halt('卡牌信息异常');
          }
          await tx.userHoldCard.create({
            data: {
              cardId: card.id,
              userId: user.id,
            },
          });

          return `恭喜您获得《${card.title}》卡牌*1`;
        }
        return halt('无效口令');
      });
    });
  }
}
